import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:inmotion_pro/config/const.dart';
import 'package:inmotion_pro/extension/future_error_handler.dart';
import 'package:inmotion_pro/http/api_helper_account.dart';
import 'package:inmotion_pro/pages/mine/setting/account_security/verify_code/verify_code_param.dart';
import 'package:inmotion_pro/pages/mixin/account_security_mixin.dart';
import 'package:lx_widgets_library/alert/loading.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

import '../../../../../http/api_helper.dart';
import '../../../../../l10n/local.dart';
import '../../../../../routes/app_routes.dart';
import '../../../../models/user_model.dart';
import 'state.dart';

class VerifyCodeController extends GetxController with AccountSecurityMixin {
  // 状态
  final VerifyCodeState state = VerifyCodeState();

  // 验证码倒计时定时器
  Timer? _timer;

  @override
  void onInit() {
    super.onInit();

    // 获取传递的参数
    if (Get.arguments != null && Get.arguments is VerifyCodeParam) {
      state.param = Get.arguments;
      // 开始倒计时
      startCountdown();
    } else {
      debugPrint("❌ VerifyCodeController: Missing or invalid VerifyCodeParam");
      Get.back();
    }
  }

  @override
  void onClose() {
    _timer?.cancel();
    super.onClose();
  }

  // 开始倒计时
  void startCountdown() {
    state.countdownTime.value = 60;
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (state.countdownTime.value > 0) {
        state.countdownTime.value--;
      } else {
        timer.cancel();
      }
    });
  }

  // 验证验证码
  Future<void> verifyCode(String code) async {
    if (code.length != verificationCodeLength) return;
    Loading.showLoading(null);
    ApiHelper()
        .verifyVerificationCode(
            account: state.param.account ?? '',
            platform: state.param.platform ?? CodePlatform.email,
            codeType: state.param.codeType ?? CodeType.security,
            code: code)
        .then((token) {
      debugPrint('✅ Verification code verified successfully, token: $token');
      Loading.dismiss();
      // 跳转到验证完成页面
      state.param.securityToken = token;
      Get.toNamed(AppRoutes.VERIFY_COMPLETE, arguments: state.param);
    }).catchErrorHandler();
  }

  // 重新发送验证码
  resendCodeOnTap() {
    if (state.countdownTime.value > 0) return;
    // 重新发送验证码逻辑
    accountSecurityRequestVerificationCode(
            account: state.param.account ?? '',
            platform: state.param.platform ?? CodePlatform.email,
            codeType: state.param.codeType ?? CodeType.security)
        .then((success) {
      if (success) {
        Loading.showToast(local.send_verification_code_success);
      } else {
        Loading.dismiss();
      }
    }).catchErrorHandler();
  }
}
